<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, toRefs, watch } from 'vue';
import { formatValue } from '@/components/PriceComponent/utils';

type ValueInputFieldProps = {
  value: string;
  defaultFormattedValue: string;
};

type ValueInputFieldEmits = {
  (e: 'change', value: string): void;
};

const props = defineProps<ValueInputFieldProps>();
const emit = defineEmits<ValueInputFieldEmits>();

const { value: originalValue } = toRefs(props);

const innerValue = ref(originalValue.value);
const isFocused = ref(false);

const displayedValue = computed(() => {
  if (isFocused.value) {
    return innerValue.value;
  }

  return formatValue(originalValue.value, props.defaultFormattedValue);
});

const handleFocus = (event: Event) => {
  isFocused.value = true;
  nextTick(() => (event.target as HTMLInputElement).select());
};

const handleBlur = () => {
  isFocused.value = false;
  const numericValue = Number(innerValue.value);

  if (numericValue < 0) {
    innerValue.value = '0';
  }

  emit('change', innerValue.value);
};

const handleInput = (event: Event) => {
  innerValue.value = (event.target as HTMLInputElement).value;
};

const handleCancel = () => {
  innerValue.value = originalValue.value;
};
</script>

<template>
  <input
    placeholder="Value"
    type="number"
    step="0.01"
    :value="displayedValue"
    @input="handleInput"
    @focus="handleFocus"
    @blur="handleBlur"
    @keydown.esc.stop="handleCancel"
    :title="originalValue || 'No value'"
    min="0"
  />
</template>

<style scoped lang="scss"></style>
